package com.zengqingfa.designpattern.create.singleton;

import java.io.*;
import java.lang.reflect.Constructor;

/**
 * @fileName: Singleton11
 * @author: zengqf3
 * @date: 2021-4-5 21:00
 * @description: 静态初始化实现单例（饿汉式）
 */
public class Singleton11 implements Serializable {

    /**
     * 构造函数私有
     */
    private Singleton11() {
        // instance 不为空，说明单例对象已经存在
        if (instance != null) {
            throw new RuntimeException("单例模式禁止反射调用！");
        }
    }

    /**
     * 静态初始化
     */
    public static Singleton11 instance = new Singleton11();

    /**
     * 获取实例
     *
     * @return
     */
    public static Singleton11 getInstance() {
        return instance;
    }

    public static void main(String[] args) throws Exception {
        Singleton11 singleton11 = Singleton11.getInstance();

        //反射
        Class clazz = Singleton11.class;
        Constructor constructor = clazz.getDeclaredConstructor();
        constructor.setAccessible(true);
        //Caused by: java.lang.RuntimeException: 单例模式禁止反射调用！
        Singleton11 newSingleton11 = (Singleton11) constructor.newInstance();
    }
}
